package com.example.demoapp.fragment;

import static com.example.demoapp.bean.util.KeyBoardUtils.hintKeyboard;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.demoapp.R;
import com.example.demoapp.activity.SearchInfoActivity;
import com.example.demoapp.config.URLs;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AudioFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AudioFragment extends Fragment {



    //mContext
    private Context mContext;
    //tabLayout
    private TabLayout tab_layout;
    //ViewPager2
    private ViewPager2 view_pager;
    //tabLayout标题
    private List<String> tabTitles;
    //切换的Fragment
    private List<Fragment> fragmentList;

    SmartRefreshLayout smartRefreshLayout;
    private int currentPage;
    private int selectedIndex;
    private SearchView searchview;

    public AudioFragment() {
    }

    public static DocumentsFragment newInstance() {
        return new DocumentsFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        currentPage = 1;
        selectedIndex=0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_audio, container, false);
        //初始化视图
        initView(view);
        //初始化Fragment
        initFragment();
        //初始化tab
        initTab();
        return view;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        // 设置ViewPager的适配器
        view_pager.setAdapter(new AudioFragment.FragmentAdapter(getActivity(), fragmentList));
        //最大预加载
        view_pager.setOffscreenPageLimit(fragmentList.size());
        // 创建TabLayout和ViewPager2之间的关联
        new TabLayoutMediator(tab_layout, view_pager,
                (tab, position) -> tab.setText(tabTitles.get(position))).attach();
        //当tab改变是调用View.post()方法来请求在下一帧中重新绘制视图，解决空白的问题
        tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                view_pager.setCurrentItem(tab.getPosition(), true);
                view_pager.post(() -> view_pager.requestLayout());
                selectedIndex = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }
    //视图绑定
    private void initView(View view) {
        //tab
        tab_layout =  (TabLayout) view.findViewById(R.id.tab_layout);
        //ViewPager2
        view_pager =  (ViewPager2) view.findViewById(R.id.view_pager);
        smartRefreshLayout = view.findViewById(R.id.smartRefreshLayout);
        setHintKeyboardView(view);
        MaterialHeader materialHeader = (MaterialHeader) smartRefreshLayout.getRefreshHeader();
        materialHeader.setColorSchemeColors(getResources().getColor(R.color.theme_color));
        // 设置下拉刷新监听器
        smartRefreshLayout.setOnRefreshListener(smartRefreshLayout -> {
            // 执行刷新操作的代码
            ChildFragment currentFragment = (ChildFragment) fragmentList.get(selectedIndex);
            currentFragment.setPage(1);
            currentFragment.refreshData();
            smartRefreshLayout.finishRefresh();//传入false表示刷新失败
            Toast.makeText(mContext, "刷新成功", Toast.LENGTH_SHORT).show();
        });

        // 设置上拉加载监听器
        smartRefreshLayout.setOnLoadMoreListener(smartRefreshLayout -> {
            ChildFragment currentFragment = (ChildFragment) fragmentList.get(selectedIndex);
            currentFragment.loadMoreData();
            smartRefreshLayout.finishLoadMore();//传入false表示加载失败
        });

        View view1=(View)view.findViewById(R.id.toptoolbar);
        searchview = view1.findViewById(R.id.searchview);
        searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String queryText) {
                return false;
            }

            @Override
            public boolean onQueryTextSubmit(String queryText) {
                Log.d("submit", "onKey: ");
                //更新新的数组信息
                Intent i = new Intent(mContext, SearchInfoActivity.class);
                i.putExtra("keyword",queryText);
                mContext.startActivity(i);
                return true;
            }
        });
    }
    //初始化Tab
    private void initTab() {
        tabTitles =new ArrayList<>();
        Collections.addAll(tabTitles, URLs.audio_tabName);
        //设置tab可以滑动
        tab_layout.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置指示器选中与未选中时的颜色
        int selectedColor = ContextCompat.getColor(mContext, R.color.tab_top_text_2);
        int unselectedColor = ContextCompat.getColor(mContext, R.color.tab_top_text_1);
        tab_layout.setTabTextColors(unselectedColor, selectedColor);
        //指示器颜色
        int indicatorColor = ContextCompat.getColor(mContext, R.color.theme_color);
        tab_layout.setSelectedTabIndicatorColor(indicatorColor);
    }

    //初始化Fragment
    private void initFragment() {
        fragmentList = new ArrayList<>();
        for (String s : URLs.audio_tabName) {
            fragmentList.add(new ChildFragment(URLs.music_list,s,3, 1));
            currentPage = 1;
        }
    }

    /**
     * FragmentAdapter，管理Fragment
     */
    private static class FragmentAdapter extends FragmentStateAdapter {
        private final List<Fragment> fragmentList;

        public FragmentAdapter(FragmentActivity activity, List<Fragment> fragmentList) {
            super(activity);
            this.fragmentList = fragmentList;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return fragmentList.size();
        }

    }
    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hintKeyboard(getActivity());
                    searchview.clearFocus();
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }
}